package com.miao.admin.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.miao.admin.entity.vo.ProductVO;
import com.miao.admin.service.AdminProductService;
import com.miao.common.entity.R;
import com.miao.common.entity.pojo.Product;
import com.miao.common.entity.search.ProductES;
import com.miao.common.utils.JWTUtil;
import com.miao.websecurity.entity.Admin;
import com.miao.websecurity.service.AdminService;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.RestStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;


/**
 * 商品表(Product)表控制层
 *
 * @author MiaoWenqing
 * @since 2021-02-03 13:46:24
 */
@RestController
@RequestMapping("admin/product")
public class AdminProductController {
    /**
     * 服务对象
     */
    @Resource
    private AdminProductService adminProductService;
    @Resource
    private AdminService adminService;


    @Resource(name = "RestHighLevelClient")
    private RestHighLevelClient restHighLevelClient;


    /**
     * 新品商品添加
     *
     * @param product 商品
     * @return R
     */
    @Transactional
    @PostMapping("/add")
    public R productAdd(@RequestBody Product product, @RequestHeader(value = "access-token") String token) {

        String s = JWTUtil.analysisToken(token);
        Map map = JSON.parseObject(s, Map.class);
        Admin admin = this.adminService.getById(map.get("adminId").toString()); //1平台 0店铺
        long id = IdWorker.getId();
        product.setStoreId(Integer.parseInt(admin.getStoreId()));
        product.setProId(String.valueOf(id));
        product.setProDis(0);
        product.setIsDiscount(false);

        if (this.adminProductService.save(product)) {
            if (this.editSearch(product)) {
                return R.ok();
            } else {
                if (this.editSearch(product)) {
                    return R.ok();
                } else {
                    this.adminProductService.removeById(id);
                }
            }
        }
        return R.error();

    }


    /**
     * 商品信息修改
     *
     * @param product 商品
     * @return R
     */
    @PostMapping("/edit")
    @Transactional
    public R productEdit(@RequestBody Product product) {

        if (this.adminProductService.updateById(product)) {
            if (this.editSearch(product)) {
                return R.ok();
            }
        }
        return R.error();

    }


    /**
     * 商品删除
     *
     * @param productId 商品ID
     * @return R
     */
    @GetMapping("/del")
    @Transactional
    public R productDel(String productId) {
        if (this.adminProductService.removeById(productId)) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    /**
     * 商品 是否上架修改
     *
     * @param productId 商品id
     * @return R
     */
    @GetMapping("/show")
    @Transactional
    public R productShow(String productId) {
        Product product = this.adminProductService.getById(productId);
        product.setIsShow(!product.getIsShow());
        if (this.adminProductService.saveOrUpdate(product)) {
            return R.ok();
        } else {
            return R.error();
        }
    }


    /**
     * 商品打折信息修改
     *
     * @param productId 商品Id
     * @param dis       折扣
     * @param isDis     是否打折
     * @return R
     */
    @GetMapping("/disCount")
    @Transactional
    public R productDiscount(String productId, int dis, boolean isDis) {
        Product product = this.adminProductService.getById(productId);
        product.setIsDiscount(isDis);
        product.setProDis(dis);
        if (this.adminProductService.saveOrUpdate(product)) {
            if (this.editSearch(product)) {
                return R.ok();
            }
        }
        return R.error();
    }


    /**
     * 商品全部信息
     *
     * @return R
     */
    @GetMapping("/storeAll")
    public R productAll(@RequestHeader(value = "access-token") String token) {
        String s = JWTUtil.analysisToken(token);
        Map map = JSON.parseObject(s, Map.class);
        Admin admin = this.adminService.getById(map.get("adminId").toString()); //1平台 0店铺
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
        productQueryWrapper.eq("store_id", admin.getStoreId());
        List<Product> products = this.adminProductService.list(productQueryWrapper);
        return R.ok(products);

    }


    public boolean editSearch(Product product) {
        ProductES productES = new ProductES();
        productES.setDiscount(product.getIsDiscount());
        productES.setProClass(product.getProClass());
        productES.setProDis(product.getProDis());
        productES.setProIcon(product.getProIcon());
        productES.setStoreId(product.getStoreId());
        productES.setProPrice(product.getProPrice());
        productES.setProTitle(product.getProTitle());
        productES.setProName(product.getProName());
        productES.setProId(product.getProId());
        IndexRequest indexRequest = new IndexRequest("miaoshop");

        indexRequest.id(productES.getProId()).source(JSON.toJSONString(productES), XContentType.JSON);
        try {
            int status = this.restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT).status().getStatus();
            if (status == 200 || status == 201) {
                return true;
            } else {
                return false;
            }

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 获取打折商品信息
     *
     * @param storeId 店铺id
     * @return R
     */
    @GetMapping("/getDisCountPro")
    public R disCountPro(String storeId) {
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
        productQueryWrapper.eq("store_id", storeId);
        productQueryWrapper.eq("is_discount", true);
        productQueryWrapper.eq("is_show", true);
        productQueryWrapper.select("pro_id", "store_id", "pro_name", "pro_title", "pro_price", "pro_dis", "pro_cost", "pro_icon");
        List<Product> list = this.adminProductService.list(productQueryWrapper);
        return R.ok(list);
    }

    /**
     * 获取非打折商品信息
     *
     * @param storeId 店铺id
     * @return R
     */
    @GetMapping("/getNoDisCountPro")
    public R noDisCountPro(String storeId) {
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
        productQueryWrapper.eq("store_id", storeId);
        productQueryWrapper.eq("is_discount", false);
        productQueryWrapper.eq("is_show", true);
        productQueryWrapper.select("pro_id", "store_id", "pro_name", "pro_title", "pro_price", "pro_dis", "pro_cost", "pro_icon");
        List<Product> list = this.adminProductService.list(productQueryWrapper);
        return R.ok(list);
    }


}